package zhongbo.java.air.flightpath.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import zhongbo.java.air.flightpath.config.RedisListenerConfig;
import zhongbo.java.air.flightpath.model.FlightPath;
import zhongbo.java.air.flightpath.service.IFlightPathService;

/**
 * 说明：
 * log_chanel 频道的消息接收器
 *
 * @author 钟波dellNotebook
 * @since 2025年04月08日 星期二 01:22:26
 */
@Component
@Slf4j
public class RedisSubscribeIngestFlightPathChanelListener implements MessageListener {

    @Autowired
    private IFlightPathService<FlightPath> flightPathService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 消息处理方法
     *
     * @param message 消息内容对象
     * @param chanel  字节数组方式的频道名称
     */
    @Override
    public void onMessage(Message message, byte[] chanel) {
        byte[] messageBody = message.getBody();
        String msgString = new String(messageBody);
        log.info("收到清洗后航迹消息 {}", msgString);
        doConvert(msgString);
    }

    private void doConvert(String msgString) {
        JSONObject jsonObject = JSONUtil.parseObj(msgString);
        FlightPath flightPath = jsonObject.toBean(FlightPath.class);
        flightPath.setId(null);
        flightPathService.add(flightPath);
        log.info("成功保存航迹信息: {}", flightPath);

        // 推送live_flight_path_[你的名字拼音]频道
        String jsonStr = JSONUtil.toJsonStr(flightPath);
        redisTemplate.convertAndSend(RedisListenerConfig.LIVE_NAME_OF_CHANEL, jsonStr);
        log.info("成功推送实时航迹信息到: {}", RedisListenerConfig.LIVE_NAME_OF_CHANEL);
    }

}
